package edu.ustb.controller.xiumi;

import com.alibaba.fastjson.JSONObject;
import edu.ustb.service.xiumi.impl.xiumiMailControllerServiceImpl;
import edu.ustb.service.xiumi.xiumiMailControllerService;
import edu.ustb.utils.MakeAuthCode;
import edu.ustb.utils.SendMail;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "xiumiMail", value = "/xiumiMail.do")
public class xiumiMailController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        // 获取用户名或手机号及邮箱号
        String info = request.getParameter("info");
        String mail = request.getParameter("mail");
        JSONObject json = new JSONObject();
        // 从数据库中查找并判断当前用户输入的邮箱是否正确
        xiumiMailControllerService service = new xiumiMailControllerServiceImpl();
        if(service.verifyInfoByMail(info, mail)){
            // 验证成功，邮箱号与用户匹配，生成验证码
            String authCode = MakeAuthCode.getAuthCode(6);
            // 发送邮件
            SendMail.SendMails(authCode, mail);
            System.out.println("邮箱正确");

            json.put("status", "true");
            json.put("authCode", authCode);
            json.put("message", "邮箱验证成功，已发送验证码");
            response.getWriter().println(json);
        }else{
            json.put("status", "false");
            json.put("authCode", null);
            json.put("message", "邮箱错误，请重新核对后输入");
            response.getWriter().println(json);

        }
    }
}
